﻿using AntdUI;
using S7SingalTool.Forms;
using S7SingalTool.Models;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace S7SingalTool.Controls
{
    public partial class TechniqueTemplatePage : BaseUserControl
    {
        public TechniqueTemplatePage()
        {
            InitializeComponent();
        }
        CksTechniqueTemplate Context = null;
        BindingList<CksTechniqueTemplate> TemplateSource = new BindingList<CksTechniqueTemplate>();
        BindingList<CksTechniqueTemplate> FieldSource = new BindingList<CksTechniqueTemplate>();
        private void TechniqueTemplatePage_Load(object sender, EventArgs e)
        {
            InitTemplateTable();
            InitFieldTable();
            ReflushData();
        }

        private void InitTemplateTable()
        {
            table1.EditMode = TEditMode.None;
            table1.Columns = new ColumnCollection();
            table1.Columns.Add(new Column("Name", "模板名称"));
            //table1.Columns.Add(new Column("Notes", "备注"));

            table1.Bordered = true;
            table1.EnableHeaderResizing = true;
            table1.EmptyHeader = true;
            table1.Gap = 6;
            table1.VisibleHeader = false;

            table1.CellClick += Table1_CellClick;
        }

        private void Table1_CellClick(object sender, TableClickEventArgs e)
        {
            var config = e.Record as CksTechniqueTemplate;
            Context = config;
            if (e.Button == MouseButtons.Left)
                LoadCheckData(Context);
        }

        private void InitFieldTable()
        {
            table2.EditMode = TEditMode.Click;
            table2.Columns = new ColumnCollection();

            table2.Columns.Add(new Column("Sequence", "顺序") { });
            table2.Columns.Add(new Column("Name", "参数名"));
            table2.Columns.Add(new Column("DataId", "数据ID"));
            table2.Columns.Add(new ColumnRadio("IsPrimary", "主键"));


            //table2.Columns.Add(new Column("LanguageKey", "翻译Key"));

            table2.Bordered = true;
            table2.EnableHeaderResizing = true;
            table2.EmptyHeader = true;
            table2.Gap = 6;
            table2.VisibleHeader = true;
            table2.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };

            table2.CellClick += (s, e) =>
            {
                var config = e.Record as CksTechniqueTemplate;
                if (e.Button == MouseButtons.Right)
                    ShowRightButton(table2, config);
            };
            table2.CellClick += Table2_CellClick;
        }

        private void ShowRightButton(Table tb, CksTechniqueTemplate item)
        {

        }

        private void Table2_CellClick(object sender, TableClickEventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var res = new TechniqueTemplateForm().ShowDialog();
            if (res == DialogResult.OK)
            {
                ReflushData();
            }
        }

        private void ReflushData()
        {
            string search = txtSearch.Text;
            TemplateSource.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksTechniqueTemplate>()
                   .WhereIF(!search.IsNullOrEmpty(), (a) => a.Name.Contains(search))
                   .Where(a => a.Type == 1)
                   .OrderBy(a => a.Sequence)
                   .ToList();
            foreach (var item in lst)
            {
                TemplateSource.Add(item);
            }
            this.table1.Binding(TemplateSource);
            if (TemplateSource.Count > 0)
            {
                if (table1.SelectedIndex < 1)
                {
                    table1.SelectedIndex = 1;
                    Context = TemplateSource[0];
                    LoadCheckData(Context);
                }
                else
                {
                    Context = TemplateSource[table1.SelectedIndex - 1];
                    LoadCheckData(Context);
                }
            }
            else
            {
                //没有数据清理另外两个表
                LoadCheckData(null);
            }
        }

        private void LoadCheckData(CksTechniqueTemplate context)
        {
            FieldSource.Clear();
            if (context == null)
                return;
            FieldSource.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksTechniqueTemplate>().Where(a => a.ParentId == context.Id).OrderBy(a => a.Sequence).ToList();
            foreach (var item in lst)
            {
                FieldSource.Add(item);
            }
            this.table2.Binding(FieldSource);
        }

        private void btnReflush_Click(object sender, EventArgs e)
        {
            ReflushData();
        }

        private void btnOpenEdit_Click(object sender, EventArgs e)
        {
            if (Context == null)
                return;
            var res = new TechniqueTemplateForm(Context).ShowDialog();
            if (res == DialogResult.OK)
            {
                ReflushData();
            }
        }

        private void btnAddParam_Click(object sender, EventArgs e)
        {
            if (Context == null)
                return;
            FieldSource.Add(new CksTechniqueTemplate() { Type = 2, ParentId = Context.Id, Sequence = 99 });
        }

        private void btnSaveField_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            var items = FieldSource.ToList().OrderBy(a => a.Sequence).ToList();
            if (items.Find(a => a.IsPrimary) == null)
            {
                MessageError("必须设置主码");
                return;
            }

            var db = SqlSugarHelper.MesDB;
            foreach (var item in items)
            {

                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                    db.Updateable(item).ExecuteCommand();
            }
            ReflushData();
            MessageInfo("OK");
        }

        private void btnDeleteTemplate_Click(object sender, EventArgs e)
        {
            var result = MessageBoxWarn("删除警告", "确认要删除吗");
            if (result != DialogResult.OK)
                return;
            if (table1.SelectedIndex < 0)
                return;
            var db = SqlSugarHelper.MesDB;
            var row =TemplateSource[table1.SelectedIndex - 1];
            db.Deleteable<CksTechniqueTemplate>().Where(a => a.ParentId == row.Id).ExecuteCommand();
            db.Deleteable(row).ExecuteCommand();
            TemplateSource.Remove(row);
            FieldSource.Clear();
        }

        private void btnDeleteField_Click(object sender, EventArgs e)
        {
            if (table2.SelectedIndex < 0)
                return;
            var result = MessageBoxWarn("删除警告", "确认要删除吗");
            if (result != DialogResult.OK)
                return;
            var db = SqlSugarHelper.MesDB;
            var row = FieldSource[table1.SelectedIndex - 1];
            db.Deleteable(row).ExecuteCommand();
            FieldSource.Remove(row);
            ReflushData();
        }
    }
}
